package cubelabs.nexus.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.SocialAuthManager;
import org.brickred.socialauth.spring.bean.SocialAuthTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cubelabs.nexus.entity.User;
import cubelabs.nexus.service.NexusService;

@Controller
public class AuthController {

	@Autowired
	private SocialAuthTemplate socialAuthTemplate;
	
	@Autowired
	private NexusService nexuService;

	@RequestMapping(value = "/authSuccess")
	public String getRedirectURL(final HttpServletRequest request)
			throws Exception {
		
		SocialAuthManager manager = socialAuthTemplate.getSocialAuthManager();
		AuthProvider provider = manager.getCurrentAuthProvider();
		
		System.out.println(provider.getUserProfile().toString());
		
		User user = nexuService.fetchUserByEmail(provider.getUserProfile().getEmail());
			if(user == null){
				user = nexuService.createUser(provider.getUserProfile());
			}
			
		
			request.getSession().setAttribute("user", user);
			
			return "redirect:/";		
		}
	
	@RequestMapping(value = "/logout")
	public String logoutUser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		request.getSession().removeAttribute("user");
		SocialAuthManager manager = socialAuthTemplate.getSocialAuthManager();
		manager.disconnectProvider(manager.getCurrentAuthProvider().getProviderId());
		
		return "redirect:/";
	}
	
	@RequestMapping(value="/denied")
	public String homePage(){
			
	 return "redirect:/";
	}



}
